package com.example.controller;

import com.example.entity.Manager;
import com.example.entity.MyResponseEntity;
import com.example.service.ManagerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author fyx
 */
@RestController
@RequestMapping("/managerUser")
@RequiresRoles("admin")
public class ManagerController {
    private final ManagerService managerService;

    public ManagerController(ManagerService managerService) {
        this.managerService = managerService;
    }

    @PostMapping
    public MyResponseEntity<?> addManager(@RequestBody Manager manager) {
        boolean isSuccess = managerService.addManager(manager);
        if (isSuccess) {
            return new MyResponseEntity<>(200, "添加成功", manager);
        }
        return new MyResponseEntity<>(400, "添加失败", null);
    }

    @DeleteMapping("/{id}")
    public MyResponseEntity<?> deleteManager(@PathVariable int id) {
        if (managerService.deleteManager(id)) {
            return new MyResponseEntity<>(200, "删除成功", null);
        }
        return new MyResponseEntity<>(404, "删除失败, 无该manager", null);
    }

    @PutMapping
    public MyResponseEntity<?> updateManager(@RequestBody @Valid Manager manager) {
        // 若manager对象id为空，会产生空指针异常，已使用全局异常捕捉该异常，无需手动处理
        if (managerService.updateManager(manager)) {
            return new MyResponseEntity<>(200, "修改成功", null);
        }
        return new MyResponseEntity<>(404, "修改失败", null);
    }

    @GetMapping("/{id}")
    public MyResponseEntity<?> findManager(@PathVariable int id) {
        final Manager manager = managerService.findManagerById(id);
        return new MyResponseEntity<>(200, "查询成功", manager);
    }

    @GetMapping("/{startPage}/{pageSize}")
    public MyResponseEntity<?> findAllRes(@PathVariable("startPage") int startPage, @PathVariable("pageSize") int pageSize) {
        PageHelper.startPage(startPage, pageSize);
        List<Manager> managers = managerService.findAll();
        PageInfo<Manager> pageInfo = new PageInfo<>(managers);
        return new MyResponseEntity<>(200, "查询成功", pageInfo);
    }


}
